import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

class LoadingUtil {
  static LoadingUtil? _instance;

  LoadingUtil._();

  static Future<void> show({
    String? desc,
    Duration? timeout,
    void Function(LoadingUtil instance)? onLoading,
    void Function()? onClose,
    void Function()? onTimeout,
  }) async {
    Timer? timeoutTimer;
    bool isTimeout = false;
    onLoading?.call(_instance ??= LoadingUtil._());
    if (timeout != null) {
      timeoutTimer = Timer(timeout, () {
        isTimeout = true;
        SmartDialog.dismiss(status: SmartStatus.loading);
      });
    }
    return SmartDialog.showLoading(
      msg: desc ?? '等待请求响应',
      alignment: Alignment.center,
      maskColor: Colors.black.withOpacity(.1),
      animationTime: const Duration(milliseconds: 150),
      clickMaskDismiss: false,
      backDismiss: false,
      displayTime: timeout,
      onDismiss: () {
        if (isTimeout) {
          onTimeout?.call();
        } else {
          timeoutTimer?.cancel();
          onClose?.call();
        }
      },
    );
  }

  Future<void> close() async => SmartDialog.dismiss(status: SmartStatus.loading);
}
